import React, { Component } from 'react';
import ReactEcharts from 'echarts-for-react';
import axios from '../api'
import xyz from './xyz'

import echarts from 'echarts';

require('echarts/map/js/china.js');

export default class GeoDist extends Component {
  constructor(props) {
    super(props);
    this.state = {
      option: {
        visualMap: {
          type: 'continuous',
          show: false,
          inRange: {
            color: ['#2f54eb', '#40a9ff', '#13c2c2', '#ffec3d', '#ffa940', '#ff7a45', '#ff4d4f', '#f759ab'],
          }
        },
        series: []
      },
    };
  }

  componentWillMount () {
    echarts.registerTheme('xyz', xyz);
  }

  componentDidMount () {
    this.tick()
    this.timerID = setInterval(
      () => this.tick(),
      15 * 60 * 1000
    );
  }

  componentWillUnmount () {
    clearInterval(this.timerID);
  }

  tick () {
    axios.get('/user_sta').then(({ data: { district, total } }) => {
      this.genData(district, total)
    })
  }

  genData (district, total) {
    const data = district.map(item => Object.assign({}, item, { name: item.name.replace(/[省自治区回壮维吾尔族]+/g, '') }))
    const { option } = this.state
    const series = [{
      type: 'map',
      mapType: 'china',
      left: 0,
      roam: false,
      data,
      itemStyle: { areaColor: '#5F636F' }
    }, {
      type: 'pie',
      center: ['80%', '50%'],
      radius: ['40%', '50%'],
      right: 0,
      label: { show: true, position: 'inside', color: '#fff' },
      labelLine: { show: false },
      data
    }, {
      type: 'pie',
      center: ['80%', '50%'],
      radius: ['58%', '59%'],
      right: 0,
      label: { show: true, position: 'outside', formatter: '{@value}%' },
      labelLine: { show: false, length: 0, length2: 5 },
      itemStyle: { opacity: 0.5 },
      data
    }, {
      type: 'pie',
      center: ['80%', '50%'],
      radius: ['38%', '38%'],
      right: 0,
      label: { show: true, position: 'center', color: '#fff', fontSize: 17, formatter: ['总人数', `${total}`].join('\n') },
      data: [total]
    }]

    this.setState({ option: Object.assign({}, option, { series }) })
  }

  render () {
    return (
      <ReactEcharts
        option={this.state.option}
        notMerge={true}
        lazyUpdate={true}
        style={{ height: '100%' }}
        theme={'xyz'} />
    );
  };
}